package com.viknix.threadpool.manager.autoconfigure;

import com.viknix.threadpool.manager.client.config.ApplicationContextHolder;
import com.viknix.threadpool.manager.client.config.Launch;
import com.viknix.threadpool.manager.client.core.*;
import com.viknix.threadpool.manager.client.global.DynamicThreadPoolBannerHandler;
import com.viknix.threadpool.manager.client.http.HttpAgent;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

/**
 * @Author: Dongqi
 * @Date: 2021/10/21 13:32
 * @Version 1.0
 * @Description
 */
@Configuration
@AllArgsConstructor
@ConditionalOnBean(Launch.class)
@EnableConfigurationProperties(TpmConfigProperties.class)
@ImportAutoConfiguration({HttpClientConfig.class, TpmDiscoveryConfig.class, TpmAlertConfig.class})
public class TpmConfigAutoConfiguration {

    private final TpmConfigProperties properties;

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE) // 最高优先级
    public ApplicationContextHolder applicationContextHolder() {
        return new ApplicationContextHolder();
    }

    @Bean
    public DynamicThreadPoolBannerHandler threadPoolBannerHandler() {
        return new DynamicThreadPoolBannerHandler(properties.isBanner());
    }

    /**
     * 配置动态线程池的配置行为对象
     *
     * @param httpAgent
     * @return
     */
    @Bean
    @SuppressWarnings("all")
    public ConfigService configService(TpmConfigProperties tpmConfigProperties, HttpAgent agent) {
        return TpmConfigManager.createConfigService(tpmConfigProperties, agent);
    }

    /**
     * 配置动态线程池的后置处理器
     *
     * @param threadPoolOperation
     * @param applicationContextHolder
     * @return
     */
    @Bean
    @SuppressWarnings("all")
    public DynamicThreadPoolPostProcessor threadPoolBeanPostProcessor(HttpAgent httpAgent, ApplicationContextHolder applicationContextHolder, ConfigService configService) {
        return new DynamicThreadPoolPostProcessor(properties.getProjectId(), properties.getNamespace(), httpAgent, configService);
    }
}
